﻿using HalconDotNet;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using VisionServices.Halcon.Common;

namespace WpfUILib.IControl.Vision
{
    /// <summary>
    /// HDisplay.xaml 的交互逻辑
    /// </summary>
    public partial class HDisplay : UserControl
    {
        public HDisplay()
        {
            InitializeComponent();
           
            HOperatorSet.SetWindowAttr("background_color", "dim gray");
            // 初始化时绑定事件
            HS.HMouseMove += HS_MouseMove;
        }



        private void HS_MouseMove(object sender, HSmartWindowControlWPF.HMouseEventArgsWPF e)
        {
            HTuple gray = 0;
            if (ImageData != null && ImageWidth != 0 && (e.Row >= 0) && (e.Column >= 0) && e.Column <= ImageWidth && e.Row <= ImageHeight)
                HOperatorSet.GetGrayval(ImageData, ((int)e.Row), ((int)e.Column), out gray);
            PixelInfo.Content = $"X: {e.Column.ToString("0.0")}   Y: {e.Row.ToString("0.0")}   灰度值: {gray.I}        ";
        }



        //图像数据依赖属性
        public static readonly DependencyProperty ImageDataProperty =
                DependencyProperty.Register("ImageData", typeof(HObject), typeof(HDisplay), 
                new PropertyMetadata(null, ImageDataPropertyChanged));

        private static void ImageDataPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is HDisplay control )
            {
                control.UpdateImage();
            }
        }
        private void UpdateImage()
        {
            HTuple width, height;
            //清理
            HS.HalconWindow.ClearWindow();
            //显示图像            
            HS.HalconWindow.DispObj(ImageData);
            //显示图像宽高
            HOperatorSet.GetImageSize(ImageData, out width, out height);
            ImageWidth = width.I;
            ImageHeight = height.I;
            ImageSizeInfo.Content = $"图像宽度: {ImageWidth}   图像高度: {ImageHeight}";
            HOperatorSet.SetSystem("tsp_width", width);
            HOperatorSet.SetSystem("tsp_height", height);
            //图像充满
            HS.SetFullImagePart();
            //显示DispRegion
            if (DispRegion != null)
                foreach (var region in DispRegion)
                {
                    HS.HalconWindow.SetColor(region.Color);
                    HS.HalconWindow.DispObj(region.Region);
                }
            //显示DispString
            if (DispString != null)
                foreach (var str in DispString)
                {
                    HS.HalconWindow.SetColor(str.Color);
                    HS.HalconWindow.SetTposition(str.Row, str.Col);
                    HS.HalconWindow.SetFont("Arial" + "-Normal-" + str.Size.ToString());
                    HS.HalconWindow.WriteString(str.Text);
                }
            if(ROI!= null)
            {
                foreach (var item in ROI)
                {
                    item.DrawingObject.ClearDrawingObject();
                }
            }
        }

        //显示Region依赖属性
        public static readonly DependencyProperty DispRegionProperty = 
            DependencyProperty.Register("DispRegion",typeof(List<HDRegion>),typeof(HDisplay),
                new PropertyMetadata(null, ImageDataPropertyChanged));
        //显示文本依赖属性
        public static readonly DependencyProperty DispStringProperty =
            DependencyProperty.Register("DispString", typeof(List<HDString>), typeof(HDisplay),
                new PropertyMetadata(null, ImageDataPropertyChanged));
        //ROI数据依赖属性
        public static readonly DependencyProperty ROIProperty =
                DependencyProperty.Register("ROI", typeof(List<HDRoi>), typeof(HDisplay),
                new PropertyMetadata(null, ROIPropertyChanged));

        private static void ROIPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is HDisplay control)
            {
                control.UpdateROI();
            }
        }
        private void UpdateROI() 
        {
            foreach (var roi in ROI)
            {
                HS.HalconWindow.AttachDrawingObjectToWindow(roi.DrawingObject);
                roi.DrawingObject?.OnDrag(HDrawingObjectDragCallbackFunc);
                roi.DrawingObject?.OnResize(HDrawingObjectDragCallbackFunc);
            }
        }
        private  void HDrawingObjectDragCallbackFunc(HDrawingObject drawid, HWindow windowHandle, string type)
        {
            var row1 = drawid.GetDrawingObjectParams("row1");
            var colum1 = drawid.GetDrawingObjectParams("column1");
            var row2 = drawid.GetDrawingObjectParams("row2");
            var colum2 = drawid.GetDrawingObjectParams("column2");
            HTuple[] Tuples = { row1, colum1, row2, colum2 };
            var obj = ROI.FirstOrDefault( d => d.DrawingObject?.ID==drawid.ID );
            if (obj != null) 
            {
                obj.Location = Tuples;
            }

        }

        private int ImageWidth;
        private int ImageHeight;
        public HObject ImageData 
        {
            get=> (HObject)GetValue(ImageDataProperty);
            set=> SetValue(ImageDataProperty, value);
           
        }
        public List<HDRegion> DispRegion 
        {
            get => (List<HDRegion>)GetValue(DispRegionProperty);
            set => SetValue(DispRegionProperty, value);
        }
        public List<HDString> DispString
        {
            get => (List<HDString>)GetValue(DispStringProperty);
            set => SetValue(DispStringProperty, value);
        }
       
        public List<HDRoi> ROI 
        {
            get => (List<HDRoi>)GetValue(ROIProperty);
            set => SetValue(ROIProperty, value);
        }
        private void OpenImage_Click(object sender, RoutedEventArgs e)
        {
            HObject image;
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "图片文件(*.jpg,*.bmp,*.png,*.gif)|*.jpg;*.bmp;*.png;*.gif";
            openFileDialog.Multiselect = true;
            openFileDialog.Title = "读取图片";
            if (openFileDialog.ShowDialog() == true)
            {
                HOperatorSet.ReadImage(out image, openFileDialog.FileNames);
                ImageData = image;
                DispRegion = [];
                DispString = [];
            }
        }
        private void SaveImage_Click(object sender, RoutedEventArgs e)
        {
            if (ImageData != null)
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.RestoreDirectory = true;
                sfd.Title = "保存图片";
                if (sfd.ShowDialog() == true)
                {
                    try
                    {
                        HOperatorSet.WriteImage(ImageData, "bmp", 0, sfd.FileName);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
            else
            {
                MessageBox.Show("当前图片为空！");
            }
        }
        private void SaveWindow_Click(object sender, RoutedEventArgs e)
        {
            if (ImageData != null)
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.RestoreDirectory = true;
                sfd.Title = "保存图片";
                if (sfd.ShowDialog() == true)
                {
                    try
                    {
                        HObject image;
                        HOperatorSet.DumpWindowImage(out image, HS.HalconWindow);
                        HOperatorSet.WriteImage(image, "bmp", 0, sfd.FileName);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
            else
            {
                MessageBox.Show("当前图片为空！"); 
            }
        }

    }
}
